package com.sinopec.uhf.chengwei.net

import com.rscja.deviceapi.entity.UHFTAGInfo
import com.rscja.deviceapi.interfaces.IUHFA4
import com.sinopec.uhf.chengwei.Config
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.isActive

internal object NetCoroutineRead {

    fun readATag(
        reader: IUHFA4,
        config: Config = Config(),

        ): Flow<UHFTAGInfo?> {
        return channelFlow<UHFTAGInfo?> {
            val isStartOk = reader.startInventoryTag()
            if (!isStartOk) {
                reader.stopInventory()
                throw CancellationException("开启识别标签失败")
            }
            delay(10)
            val consumer: ((UHFTAGInfo) -> Unit) = {
                trySend(it)
            }
            while (currentCoroutineContext().isActive) {
                readTagOneTime(reader, consumer)
                delay(config.readTagOneTime)
            }

            awaitClose {
                reader.stopInventory()
            }

        }
    }


    //读一次tag
    private fun readTagOneTime(
        reader: IUHFA4,
        consumer: (UHFTAGInfo) -> Unit
    ) {
        val tag = reader.readTagFromBuffer()
        if (tag != null) {
            consumer(tag)
        }
    }


}